package com.gardenguell.salad.data.volley;


import com.android.volley.*;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.gardenguell.salad.app.AppConstant;
import com.gardenguell.salad.app.AppContext;
import com.gardenguell.salad.data.util.CacheUtil;
import com.gardenguell.salad.util.CommonLog;

import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * Created by absurd on 14-3-15.
 */
public class RequestManager {

    private static final CommonLog log = CommonLog.getInstance();

    // 设置最大宽高来限制加载到内存中的图片的大小，减少OOM的发生，当加载一些大图片时，效果还是非常明显的
    private static final int HEIGHT = 900, WIDTH = 900;

    public static RequestQueue mRequestQueue = newRequestQueue();

    // 取运行内存阈值的1/3作为图片缓存
    private static final int MEM_CACHE_SIZE = 1024 * 1024 * ((ActivityManager) AppContext.getContext()
            .getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass() / 3;

    private static ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(
            MEM_CACHE_SIZE));

    private static DiskBasedCache mDiskCache = (DiskBasedCache) mRequestQueue.getCache();

    private RequestManager() {

    }

    private static Cache openCache() {
        return new DiskBasedCache(CacheUtil.getExternalCacheDir(AppContext.getContext()),
                10 * 1024 * 1024);
    }

    private static RequestQueue newRequestQueue() {
        RequestQueue requestQueue = new RequestQueue(openCache(), new BasicNetwork(new HurlStack()));
        requestQueue.start();
        return requestQueue;
    }

    public static void addRequest(Request request, Object tag) {
        if (tag != null) {
            request.setTag(tag);
        }
        StringBuffer sb = new StringBuffer();
        sb.append(request.getMethod() == Request.Method.GET ? "GET; " : "POST; ");
        sb.append(request.getUrl() + "; ");
        try {
            if(request.getBody() != null) {
                sb.append(new String(request.getBody(), "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AuthFailureError authFailureError) {
            authFailureError.printStackTrace();
        }
        log.d(AppConstant.LOG_TAG.NETWORK_REQUEST + "--------->" + sb);
        mRequestQueue.add(request);
    }

    public static void cancelAll(Object tag) {
        mRequestQueue.cancelAll(tag);
    }

    public static File getCachedImageFile(String url) {
        return mDiskCache.getFileForKey(url);
    }

    public static ImageLoader.ImageContainer loadImage(String requestUrl,
                                                       ImageLoader.ImageListener imageListener) {
        return loadImage(requestUrl, imageListener, WIDTH, HEIGHT);
    }

    public static ImageLoader.ImageContainer loadImage(String requestUrl,
                                                       ImageLoader.ImageListener imageListener, int maxWidth, int maxHeight) {
        return mImageLoader.get(requestUrl, imageListener, maxWidth, maxHeight);
    }

    public static ImageLoader.ImageListener getImageListener(final ImageView view, final Bitmap defaultImageBitmap,
                                                             final Bitmap errorImageBitmap, final BitmapFilter bitmapFilter) {
        return new ImageLoader.ImageListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (errorImageBitmap != null) {
                    if (bitmapFilter != null) {
                        view.setImageBitmap(bitmapFilter.filter(errorImageBitmap));
                    } else {
                        view.setImageBitmap(errorImageBitmap);
                    }
                }
            }


            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                if (response.getBitmap() != null) {
                    view.setTag("loadSuccess");
                    if (!isImmediate && defaultImageBitmap != null) {
                        if (bitmapFilter != null) {
                            view.setImageBitmap(bitmapFilter.filter(response.getBitmap()));
                        } else {
                            view.setImageBitmap(response.getBitmap());
                        }
                    } else {
                        if (bitmapFilter != null) {
                            view.setImageBitmap(bitmapFilter.filter(response.getBitmap()));
                        } else {
                            view.setImageBitmap(response.getBitmap());
                        }
                    }
                } else if (defaultImageBitmap != null) {
                    if (bitmapFilter != null) {
                        view.setImageBitmap(bitmapFilter.filter(defaultImageBitmap));
                    } else {
                        view.setImageBitmap(defaultImageBitmap);
                    }
                }
            }
        };
    }

}
